/*
 * @author Stanislovas Mickus
 * @version 1
 * @date 18 December, 2014
 *
 *  Copyright (C) 2013 Stanislovas Mickus
 *
 * Licensed under the GNU General Public License, Version 3 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.gnu.org/copyleft/gpl.html
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.stasmobstudios.musicplayer.fragments;

import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.stasmobstudios.musicplayer.R;
import com.stasmobstudios.musicplayer.activities.MusicPlayerUI;
import com.stasmobstudios.musicplayer.interfaces.PlaybackServiceInterface;
import com.stasmobstudios.musicplayer.util.Fonts;
import com.stasmobstudios.musicplayer.util.MusicUtils;
import com.stasmobstudios.musicplayer.views.ClockSeekBar;

public class TrackInfoFragment extends Fragment {
    private View trackView;
    private MusicPlayerUI mMusicPlayerUI;
    private TimeUpdateTask mTimeUpdateTask;


    public TrackInfoFragment() {
        super();
    }

    /**
     * Async track time update function
     */
    private class TimeUpdateTask extends AsyncTask<Double, String, Double> {
        PlaybackServiceInterface mPlaybackService = mMusicPlayerUI.getPlaybackSrevice();

        protected Double doInBackground(Double... times) {
            double updateTime = times[0];

            // Update time information
            while (true) {
                // Wait for playback service connection
                if (mMusicPlayerUI == null || mMusicPlayerUI.getPlaybackSrevice() == null) {
                    try {
                        Thread.sleep((long) updateTime * 1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    continue;
                }

                mPlaybackService = mMusicPlayerUI.getPlaybackSrevice();
                if (mPlaybackService.isPrepared()) {
                    int currentTime = mPlaybackService.getTrackCurrentTime();
                    publishProgress(String.valueOf(currentTime));
                }

                try {
                    Thread.sleep((long) updateTime * 1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                if (isCancelled()) break;
            }

            return updateTime;
        }

        protected void onProgressUpdate(String... updateTime) {
            int currentPos = mPlaybackService.getTrackCurrentTime();
            int currentDur = mPlaybackService.getTrackDuration();
            float progress = currentPos * 1f / (currentDur == 0 ? 1 : currentDur);
            if (currentDur == 0) progress = 0;

            ((TextView) trackView.findViewById(R.id.trackTime)).setText(MusicUtils.makeTimeString(mMusicPlayerUI, currentPos / 1000));
            ((ClockSeekBar) trackView.findViewById(R.id.seekCTime)).refreshCanvasProgress(progress);
        }

        protected void onPostExecute(Double result) {
            Toast.makeText(mMusicPlayerUI, "Update interval " + result + " bytes", (Toast.LENGTH_SHORT)).show();
        }
    }

    // Initialize track info fragment view
    public void initTrackView() {
        ClockSeekBar timeCTrack = ((ClockSeekBar) trackView.findViewById(R.id.seekCTime));

        timeCTrack.refreshClockProgress(0);
        timeCTrack.setSeekBarChangeListener(new ClockSeekBar.OnSeekChangeListener() {
            @Override
            public void onProgressChange(ClockSeekBar view, int newProgress) {
                mMusicPlayerUI.getPlaybackSrevice().mediaSeekToProcent(newProgress);
            }
        });
        timeCTrack.setStopSwipeViewPager(mMusicPlayerUI.getmMusicPlayerUIViewPager());
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        this.mMusicPlayerUI = MusicPlayerUI.getMusicPlayerActivity();
        trackView = inflater.inflate(R.layout.music_track_view, container, false);
        //Update and Style Track View
        TextView artistText = (TextView) trackView.findViewById(R.id.labelArtist);
        TextView albumText = (TextView) trackView.findViewById(R.id.labelAlbumName);
        TextView songText = (TextView) trackView.findViewById(R.id.labelTrackName);
        Fonts.setCustomFont(artistText, getActivity().getAssets(), "medium");
        Fonts.setCustomFont(albumText, getActivity().getAssets(), "condensedBold");
        Fonts.setCustomFont(songText, getActivity().getAssets(), "condensed");

        return trackView;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        // Initialize track fragments controls
        mMusicPlayerUI.setOnConectedToPlaybackServiceListener(new MusicPlayerUI.OnConnectedToPlaybackServiceListener() {
            @Override
            public void onConnected() {
                initTrackView();
            }
        });
        // Update track view with first track
        mMusicPlayerUI.setOnLibraryCursorLoadFinishedListener(new MusicPlayerUI.OnLibraryCursorLoadFinishedListener() {
            @Override
            public void onLoadFinished() {
                mMusicPlayerUI.updateCurrentTrackInfo();
                mMusicPlayerUI.setOnLibraryCursorLoadFinishedListener(null);
            }
        });
    }

    @Override
    public void onPause() {
        // Start track info update task
        mTimeUpdateTask.cancel(true);

        super.onPause();
    }

    @Override
    public void onResume() {
        super.onResume();

        mTimeUpdateTask = new TimeUpdateTask();
        mTimeUpdateTask.execute((Double) 0.1d);
    }
}
